import CryptoJS from 'crypto-js';
const systemJs = {
	/**
	 * 	//顶部标题栏显示样式方法
	 * @param {Object} titleBar 标题名称
	 * @param {Object} titleShowLeft 是否显示左侧返回键
	 */
	showTitleBar: function(titleBar, titleShowLeft) {
		var navBarData = getApp().globalData.navBarData
		navBarData.titleBar = titleBar
		if (titleShowLeft) {
			navBarData.titleShowLeft = true,
				navBarData.leftIcon = 'left', //返回的图标
				navBarData.leftText = '返回'
		} else {
			navBarData.titleShowLeft = false,
				navBarData.leftIcon = '',
				navBarData.leftText = ''
		}
		getApp().globalData.navBarData = navBarData
	},
	/**
	 * 	//检测字符串是否为空
	 * 空返回  true；有值返回false
	 * @param {Object} res
	 */
	IsEmpty: function(res) {
		if (typeof res == "undefined" || res == null || res === "" || res.length < 1) {
			return true;
		} else {
			return false;
		}
	},
	/**
	 * 获取当前时间流水号字符串
	 * yyyyMMddHHmmss
	 */
	getDateTimeStr: function() {
		var now = new Date();
		var str = this.dateTimeStr('ymdhis', now);
		return str;
	},
	/**
	 * 获取当前时间字符串
	 * yyyy-MM-dd
	 * day为正数就是几天后，为负数就是几天前
	 */
	getDate: function(day = 0) {
		var now = new Date();
		now.setDate(now.getDate() + day)
		var str = this.dateTimeStr('y-m-d', now);
		return str;
	},
	/**
	 * 获取当前时间字符串
	 * yyyy-MM-dd HH:mm:ss
	 */
	getDateTime: function() {
		var now = new Date();
		var str = this.dateTimeStr('y-m-d h:i:s', now);
		return str;
	},

	/**
	 * 按照自定义格式返回时间字符串
	 * @param {String} str (y-m-d h:i:s) y:年 m:月 d:日 h:时 i:分 s:秒
	 */
	dateTimeStr: function(str, date) {
		// var date = new Date(),
		var year = date.getFullYear(); //年
		var month = date.getMonth() + 1; //月
		var day = date.getDate(); //日
		var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); //时
		var minute = date.getMinutes() < 10 ? date.getMinutes() : date.getMinutes(); //分
		var second = date.getSeconds() < 10 ? date.getSeconds() : date.getSeconds(); //秒
		month >= 1 && month <= 9 ? (month = "0" + month) : "";
		day >= 0 && day <= 9 ? (day = "0" + day) : "";
		hour >= 0 && hour <= 9 ? hour : "";
		minute >= 0 && minute <= 9 ? (minute = "0" + minute) : "";
		second >= 0 && second <= 9 ? (second = "0" + second) : "";
		if (str.indexOf('y') != -1) {
			str = str.replace('y', year)
		}
		if (str.indexOf('m') != -1) {
			str = str.replace('m', month)
		}
		if (str.indexOf('d') != -1) {
			str = str.replace('d', day)
		}
		if (str.indexOf('h') != -1) {
			str = str.replace('h', hour)
		}
		if (str.indexOf('i') != -1) {
			str = str.replace('i', minute)
		}
		if (str.indexOf('s') != -1) {
			str = str.replace('s', second)
		}
		return str;
	},
	/**
	 * //根据id获取布局的高度
	 * @param {Object} id  元素的id名称
	 * @param {Object} _this  本页面this对象
	 * @param {Object} key 赋值字段信息
	 */
	getByIdHeight(id, _this, key) {
		//获取调用的当前页面的自定义数据
		var thisData = _this.$data;
		let element = '#' + id;
		var nHeight = 0;
		const query = uni.createSelectorQuery().in(_this);
		query.select(element).boundingClientRect();
		query.selectViewport().scrollOffset();
		query.exec((res) => {
			if (res && res[0]) {
				nHeight = res[0].height;
				//给调用页面的相应定义字段赋值
				thisData[key] = nHeight;
				console.log('res' + nHeight)
				// this.listSumHeight = nHeight
			}
		});
		return nHeight;
	},
	/**
	 * 获取id元素的信息
	 * @param {Object} id
	 */
	getDomInfo: function(id) {
		return new Promise((resolve) => {
			let element = '#' + id;
			const query = uni.createSelectorQuery().in(this);
			query.select(element).boundingClientRect();
			query.selectViewport().scrollOffset();
			query.exec((res) => {
				console.log(res)
				if (res && res[0]) {
					resolve(res[0]);
				} else {
					resolve("");
				}
			});
		})
	},
	/**
	 * 返回下拉框数组中某个索引元素对应的值
	 * @param {Object} rage
	 * @param {Object} index
	 */
	selectFirstRage(rage, index) {
		var item = "";
		//默认选择第一个账套
		if (rage != undefined && rage.length > 0 && index < (rage.length)) {
			item = rage[index].value;
		}
		return item;
	},
	/**
	 * 返回下拉框数组中某个元素对应的值
	 * @param {Object} rage
	 * @param {Object} value
	 * @param {Object} key  元素字段值
	 */
	selectRage(rage, value, key = "value") {
		var item;
		//默认选择第一个账套
		if (rage != undefined && rage.length > 0) {
			if (value) {
				item = rage.find(item => item[key] == value)
			}
		}
		return item;
	},
	/**
	 * 获取基础信息下拉框默认选中项
	 * @param {Object} rage1
	 * @param {Object} rage2
	 */
	selectDefaultRage(rage1, rage2) {
		var item = "";
		if (rage2 != undefined && rage2.length > 0) {
			rage2.forEach((obj, index) => {
				if (obj.value == undefined || obj.value.length <= 0) {
					item = systemJs.selectFirstRage(rage1, 0)
				} else {
					var select = systemJs.selectRage(rage1, obj.value)
					if (select) {
						item = obj.value;
					} else {
						item = systemJs.selectFirstRage(rage1, 0)
					}
				}
			})
		} else {
			//默认选择第一个账套
			item = systemJs.selectFirstRage(rage1, 0)
		}
		return item;
	},
	/**
	 * 复制深度拷贝对象
	 * @param {Object} obj1
	 */
	copyObject: function(obj1) {
		var obj;
		obj = JSON.parse(JSON.stringify(obj1))
		return obj;
	}
}




/**
 * 数据加密解密方法
 */
const cryptoJS = {
	desKey: 'cba1238b',
	desIv: 'cba1238b',
	/**
	 * 秘钥
	 */
	getKey: function() {
		return CryptoJS.enc.Utf8.parse(this.desKey)
	},
	/**
	 * 	 偏移量
	 */
	getIv: function() {
		return CryptoJS.enc.Utf8.parse(this.desIv);
	},
	/**
	 * //DES加密
	 * @param {Object} data
	 */
	encrypt: function(data) {
		const message = CryptoJS.enc.Utf8.parse(data);
		var ciphertext = CryptoJS.DES.encrypt(data, this.getKey(), {
			iv: this.getIv(),
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		return ciphertext.toString();
	},
	/**
	 * DES解密
	 * @param {Object} data
	 */
	decrypt: function(data) {
		var bytes = CryptoJS.DES.decrypt(data.toString(), this.getKey(), {
			iv: this.getIv(),
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		return bytes.toString(CryptoJS.enc.Utf8);
	},
}
/**
 * http post get请求方法
 */
const httpUnit = {
	// baseUrl: 'http://192.168.1.2',
	// port: '8033',
	getBaseUrl: function(cName) {
		var url = "";
		if (!systemJs.IsEmpty(uni.getStorageSync('systemConfig'))) {
			var baseUrl = JSON.parse(uni.getStorageSync('systemConfig'))
			// var baseUrl = getApp().globalData.baseUrl;
			url = "http://" + baseUrl.ip + ":" + baseUrl.port;
			if (!systemJs.IsEmpty(cName)) {
				if (cName.indexOf('/') == 0) {
					url = url + cName;
				} else {
					url = url + "/" + cName;
				}
			}
		}
		return url;
	},
	/**
	 * @description POST请求
	 * @param {Object} options
	 * @param {String} options.url - 请求地址
	 * @param {Object} options.data - 传输的数据
	 * @param {Boolean} options.isLoading - 是否显示加载中 
	 */
	requestCryptoPost: function(options) {
		let obj = {
			method: 'POST'
		};
		var data = Object.assign(obj, options)
		return this.requestCrypto(data);
	},
	requestCrypto: function(options) {
		//加密数据
		let data = cryptoJS.encrypt(JSON.stringify(options.data))
		console.log(data)
		return new Promise((resolve, reject) => {
			if (options.isLoading != undefined && options.isLoading) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
			}

			var contentType = 'application/x-www-form-urlencoded'
			if (options.method == 'POST') {
				contentType = 'application/json;charset:utf-8';
			}
			var url = this.getBaseUrl(options.url);
			// #ifdef H5
			if (options.url.indexOf('/') == 0) {
				url = "/api" + options.url;
			} else {
				url = "/api/" + options.url;
			}
			// #endif
			console.log(url)
			uni.request({
				url: url,
				method: options.method || 'GET',
				data: data || '',
				header: {
					'content-type': contentType
				},
				// header: options.header || {},
				success: (res) => {
					if (options.isLoading != undefined && options.isLoading) {
						uni.hideLoading();
					}
					if (res.statusCode == 200) {
						console.log(res.data)
						let data = JSON.parse(cryptoJS.decrypt(res.data.toString()))
						console.log(JSON.stringify(data))
						resolve(data);
					} else {
						reject(res);
					}
				},
				fail: (err) => {
					if (options.isLoading != undefined && options.isLoading) {
						uni.hideLoading();
					}
					if (err.errMsg == 'request:fail timeout') {
						this.uniToast('请求超时，请重试！');
					} else if (err.errMsg == 'request:fail') {
						this.uniToast('无网络！');
					} else {
						this.uniToast('服务器繁忙');
					}
					reject(err);
				}
			})
		})
	},
	request: function(options) {
		//加密数据
		let data = JSON.stringify(options.data)
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
			uni.request({
				url: this.getBaseUrl(options.url),
				method: options.method || 'GET',
				data: data || '',
				// header: options.header || {},
				success: (res) => {
					uni.hideLoading();
					if (res.statusCode == 200) {
						let data = JSON.parse(JSON.stringify(res.data))
						resolve(data);
					} else {
						reject(res);
					}
				},
				fail: (err) => {
					uni.hideLoading();
					if (err.errMsg == 'request:fail timeout') {
						this.uniToast('请求超时，请重试！');
					} else if (err.errMsg == 'request:fail') {
						this.uniToast('无网络！');
					} else {
						this.uniToast('服务器繁忙');
					}
					reject(err);
				}
			})
		})
	},
	/**
	 * 处理吐司
	 * @param msg  吐司内容
	 * @param duration  吐司时间
	 */
	uniToast: function(msg, duration = 2000) {
		//如果不添加延迟可能会出现弹出不显示的问题
		if (msg != undefined && !systemJs.IsEmpty(msg)) {
			var timeout = setTimeout(() => {
				uni.showToast({
					title: msg,
					duration: duration,
					icon: 'none'
				})
				clearTimeout(timeout);
			}, 100)
		}
	}
}
/**
 * 扫描声音mp3播放方法
 */
const ScanAudio = {
	/**
	 * 播放提示音
	 * @param {Object} src
	 */
	play: function(src) {
		var music = null;
		music = uni.createInnerAudioContext(); //创建播放器对象
		music.autoplay = true;
		music.src = src;
		music.play(); //执行执行播放
		
		music.onError(()=>{
			music.destroy();
			music = null;
		})
		music.onPause(()=>{
			music.destroy();
			music = null;
		})
		
		// music.onEnded(() => {
		// 	//音频播放结束
		// 	music = null;
		// });
		
	},
	/**
	 * 播放正确提示音
	 */
	playRight: function() {
		this.play('../../static/mp3/right.mp3')
	},
	/**
	 * 播放错误提示音
	 */
	playError: function() {
		this.play('../../static/mp3/error.mp3')
	}
}

/**
 * 弹出对话框
 */
var dConfirm, dClose
const showDialog = {
	dialogInfo: {
		msgType: '',
		title: '',
		content: '',
		confirmText: '',
		cancelText: '',
		confirm: true,
		cancel: true,
		/**
		 * 确认事件
		 * @param {Object} callback
		 */
		dialogConfirm: function(callback) {
			dConfirm = callback
		},
		/**
		 * 取消事件
		 * @param {Object} callback
		 */
		dialogClose: function(callback) {
			dClose = callback
		}
	},
	/**
	 * 打开提示框 
	 * @param {Object} ref
	 * @param {Object} obj msgType: '',
		title: '',
		content: '',
		confirmText: '',
		cancelText: '',
		dialogConfirm: function(callback) {
			dConfirm = callback
		},
		dialogClose: function(callback) {
			dClose = callback
		}
	 */
	openDialog: function(ref, obj) {
		Object.assign(this.dialogInfo,obj);
		
		// #ifdef H5
			ref.open()
		// #endif
		// #ifdef APP-PLUS
		uni.navigateTo({
			url:'/pages/unit/commonDiaog',
			animationType:'zoom-fade-out',
			animationDuration:100
		});
		// #endif
		// this.dialogInfo = obj
		// this.Vue.$refs["alertDialog"].open()

	},
	closeDialog: function(ref) {

	},
	_dialogConfirm: function() {
		if (typeof(dConfirm) == "function") {
			dConfirm()
		}
	},
	_dialogClose: function() {
		if (typeof(dClose) == "function") {
			dClose()
		}
	}
}

/**
 * 获取基础数据
 */
const baseInfo = {
	getDeviceInfo: function() {
		// #ifdef APP-PLUS
		var deviceInfo = {}
		plus.device.getInfo({
			success: (res) => {
				deviceInfo = res
				uni.setStorageSync('uuid', res.uuid.replace(',', ''));
			},
			fail: (res) => {
				deviceInfo = res
				uni.setStorageSync('uuid', '');
			}
		})
		// #endif
	}
}

/**
 * 
 */
//是否点击按钮状态
var noClick = true;
const unitJs = {
	/**
	 * 清空对象中各个元素的值
	 * @param {Object} obj
	 */
	clearObject: function(obj) {
		for (let key in obj) {
			obj[key] = ''
		}
	},
	/**
	 * 判定扫描条码是否正确
	 * @param {Object} flag
	 */
	checkBarCodeRight: function(flag) {
		if (flag) {
			ScanAudio.playRight();
		} else {
			ScanAudio.playError();
			//长震动
			uni.vibrateLong({
				success: () => {
					console.log('succ', 'success')
				}
			})
			return;
		}
	},
	/**
	 * 创建列表item元素的显示格式
	 * @param {Object} headList
	 * @param {Object} list
	 */
	createListItemInfo: function(headList, list) {
		var listInfo = [];
		if (list != undefined && list.length > 0) {
			for (var i = 0; i < list.length; i++) {
				var itemObj = {};
				var itemList = [];
				var item = list[i] //每个item信息
				if (headList != undefined && headList.length > 0) {
					for (var r = 0; r < headList.length; r++) {
						var row = headList[r];
						var rowObj = {};
						var rowList = [];
						if (row != undefined && row.length > 0) {
							for (var c = 0; c < row.length; c++) {
								var col = row[c];
								var colObj = {};
								//显示类型(input文本框，默认为text)
								if (!systemJs.IsEmpty(col.type)) {
									colObj.type = col.type;
								}
								// 显示的字体大小
								if (!systemJs.IsEmpty(col.fontSize)) {
									colObj.fontSize = col.fontSize;
								}
								//显示的字体颜色
								if (!systemJs.IsEmpty(col.color)) {
									colObj.color = col.color;
								}
								//字体是否设置超出时自动隐藏
								if (!systemJs.IsEmpty(col.isOver)) {
									//将其转为boolean类型
									colObj.isOver = JSON.parse(col.isOver);
								}
								colObj.code = col.code;
								colObj.title = col.name;
								colObj.value = item[col.code];
								rowList.push(colObj);
							}
						}
						rowObj.content = rowList;
						itemList.push(rowObj);
					}
				}
				itemObj.list = itemList;
				listInfo.push(itemObj);
			}
		}
		return listInfo;
	},
	/**
	 * 格式化金额字符串
	 * 56,789.88
	 */
	moneyFormat: function(num, decimal = 2, split = ',') {
		/*
		  parameter：
		  num：格式化目标数字
		  decimal：保留几位小数，默认2位
		  split：千分位分隔符，默认为,
		  moneyFormat(123456789.87654321, 2, ',') // 123,456,789.88
		*/
		function thousandFormat(num) {
			const len = num.length
			return len <= 3 ? num : thousandFormat(num.substr(0, len - 3)) + split + num.substr(len - 3, 3)
		}
		if (isFinite(num)) { // num是数字
			if (num === 0) { // 为0
				return num.toFixed(decimal)
			} else { // 非0
				var res = ''
				var dotIndex = String(num).indexOf('.')
				if (dotIndex === -1) { // 整数
					res = thousandFormat(String(num))
					if (decimal > 0) {
						res = res + '.' + '0'.repeat(decimal)
					}
				} else { // 非整数
					// js四舍五入 Math.round()：正数时4舍5入，负数时5舍6入
					// Math.round(1.5) = 2
					// Math.round(-1.5) = -1
					// Math.round(-1.6) = -2
					// 保留decimals位小数
					const numStr = String((Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal))
						.toFixed(
							decimal)) // 四舍五入，然后固定保留2位小数
					const decimals = numStr.slice(dotIndex, dotIndex + decimal + 1) // 截取小数位
					res = thousandFormat(numStr.slice(0, dotIndex)) + decimals
				}
				return res
			}
		} else {
			return '--'
		}
	},
	/**
	 * 添加路由跳转拦截器
	 */
	addInterceptor: async function() {
		//不需要登陆就能跳转的页面
		const noLoginPageList = ["/pages/main/login", "/pages/main/UpdateConnectionSystem"];
		//不需要页面类型的页面列表
		const noPageCodeList = ["/pages/main/mainPage", "/pages/main/userInfo", "/pages/main/dataStatistics",
			"/pages/main/checkSystemInfo", "/pages/main/UpdatePassword"
		];
		const list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
		list.forEach((item) => {
			//添加路由拦截器
			uni.addInterceptor(item, {
				invoke: (e) => {

					//判断是否包含登陆人员的信息
					var userInfo = uni.getStorageSync('userInfo');
					if (noLoginPageList.indexOf(e.url.split('?')[0]) > -1) {
						return e;
					}

					if (!userInfo) {
						console.log(userInfo)
						console.log(e.url)
						uni.reLaunch({
							url: '/pages/main/login'
						})
						return false;
					}
					var urlArr = e.url.split('?');

					//判断跳转时是否包含页面的类型
					if (urlArr && urlArr.length > 0 && noPageCodeList.indexOf(urlArr[0]) <
						0) {
						var url = e.url;
						if (url.indexOf('?') > -1) {
							var obj = {};
							var objArr = String(url.split('?')[1]).split('&');
							for (var i = 0; i < objArr.length; i++) {
								var objStr = String(objArr[i]);
								if (!systemJs.IsEmpty(objStr)) {
									var arr = objStr.split('=');
									obj[arr[0]] = arr[1];
								}
							}
							//如果没有页面编码就跳转到主界面
							if (systemJs.IsEmpty(obj.pageCode)) {
								uni.reLaunch({
									url: '/pages/main/mainPage'
								})
								return false;
							}
						} else {
							uni.reLaunch({
								url: '/pages/main/login'
							})
							return false;
						}
					}
					return e;
				}
			})
		})
	},
	repInterceptor: async function() {
		await this.addInterceptor()
	},
	/**
	 * 扫描条形码所需对象
	 */
	scanParams: {
		/**
		 * //是否连续扫描 false(默认)| true
		 */
		// isContinuScan: false, 
		/**
		 * //扫描识别的条码类型
		 */
		scanFilter: [],
		/**
		 * //扫描成功后的回调函数
		 */
		success: async function() {},
		/**
		 * //扫描失败后的回调函数
		 */
		fail: async function() {}
	},
	/**
	 * 调取扫描页面执行扫描条码
	 * @param {Object} param 传入的对象
	 * @param {Boolean} param.isContinuScan - 是否连续扫描 false(默认)| true
	 * @param {[]} param.scanFilter - 扫描识别的条码类型为数组,二维码是'qrCode'，一维码是'barCode'
	 * @param {Object} param.ref - 扫描控件的ref对象
	 * @param {Function} param.success - 扫描成功后的回调函数
	 * @param {Function} param.fail - 扫描失败后的回调函数
	 */
	scanBarCode:  function(param) {
		// #ifdef APP-PLUS
		if (param != undefined && Object.keys(param).length > 0) {
			var obj = {};
			Object.assign(this.scanParams, param);
			var objStr = JSON.stringify(this.scanParams);
			uni.navigateTo({
				url: `/pages/unit/scanBarCode?objStr=${objStr}`,
				animationType: 'none',

			})
			// this.scanParams.ref.open()
			//监听扫码成功事件
			uni.$once('scanBarSuccess', async (result)=>{
				console.log("成功执行")
				await this.scanParams.success(result);
				await result.callback();
			})
			//监听扫码失败事件
			uni.$once('scanBarFail', async (result)=>{
				await this.scanParams.fail(result);
			})
		}
		// #endif
	},
	reStartScan:function(){
		//监听扫码成功事件
		uni.$once('scanBarSuccess',async (result)=>{
			await this.scanParams.success(result);
			await result.callback();
		})
		//监听扫码失败事件
		uni.$once('scanBarFail', async (result)=>{
			await this.scanParams.fail(result);
		})
	},
	/**
	 * 扫描成功的回调函数
	 */
	// scanCallBack: function(result) {
	// 	//执行成功的回调函数
	// 	this.scanParams.scanCallBack(result);
	// }
	/**
	 * 防止多次提交请求数据
	 * @param {any} that 传入本页面this对象，需要再data()中定义挂载noClick=true参数 
	 * @param {Function} callBack -执行的回调函数
	 */
	noMultipleClicks:function(that,callBack){
		if(that.noClick){
			that.noClick = false;
			callBack();
			setTimeout(()=>{
				that.noClick = true;
			},2500)
		}else{
			httpUnit.uniToast("您操作过于频繁，请稍后再试!")
		}
	}
}
export {
	systemJs,
	cryptoJS,
	httpUnit,
	ScanAudio,
	showDialog,
	baseInfo,
	unitJs
}